<template>
  <div class="p-2">
<!--    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">-->
<!--      <div class="mb-[10px]" v-show="pd.showSearch">-->
<!--        <el-card shadow="hover">-->
<!--          <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">-->
<!--            <el-form-item label="树节点名" prop="productName">-->
<!--              <el-input v-model="pd.queryParams.productName" placeholder="请输入树节点名" clearable style="width: 150px"-->
<!--                        @keyup.enter="handleQuery"/>-->
<!--            </el-form-item>-->
<!--            <el-form-item>-->
<!--            </el-form-item>-->
<!--          </el-form>-->
<!--        </el-card>-->
<!--      </div>-->
<!--    </transition>-->

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['demo:tree:add']">新增顶级物料
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar :search="false" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="pd.loading" :data="pd.treeList" row-key="lineId" :default-expand-all="pd.isExpandAll" ref="treeTableRef">
        <el-table-column label="物料名称" align="center" prop="productName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['demo:tree:add']">
              新增下级物料
            </el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['demo:tree:edit']">
              修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['demo:tree:remove']">删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="使用数量" align="center" prop="quantity" />
        <el-table-column label="物料状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="上级物料码" align="center" prop="parentId" />
        <el-table-column label="物料码" align="center" prop="productId" />
        <el-table-column label="BOM编码" align="center" prop="id" />
        <el-table-column label="BOM名称" align="center" prop="bomName" />
      </el-table>
    </el-card>
    <!-- 添加或修改物料对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="500px" append-to-body>
      <el-form ref="treeFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-form-item label="父id" prop="parentId">
          <el-tree-select v-model="pd.form.parentId" :data="pd.treeOptions"
                          :props="{ value: 'productId', label: 'productName', children: 'children'}"
                          value-key="id" placeholder="请选择父id" check-strictly disabled />
        </el-form-item>
        <el-form-item :label="pd.formLabel" prop="deptId">
          <ProductSearch title="物料查询" :dataText="pd.dataText" :params="{isMaterial:true}" @ok="searchProduct" />
        </el-form-item>
        <el-form-item label="物料用量" prop="userId">
          <el-input v-model="pd.form.quantity" placeholder="请输入物料用量" />
        </el-form-item>
        <el-form-item label="物料状态" prop="status">
          <el-select v-model="pd.form.status" placeholder="请选择物料状态">
            <el-option v-for="dict in sys_status" :key="dict.value" :label="dict.name" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BomLine" lang="ts">
import {addBomLine, BomLineVO, delBomLine, listBomLine, updateBomLine } from '@/views/wms/bom/api';
import ProductSearch from "@/views/wms/product/search.vue";
import {ProductVO} from "@/views/wms/product/api";

const route = useRoute();
const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const queryFormRef = ref<ElFormInstance>();
const treeFormRef = ref<ElFormInstance>();
const treeTableRef = ref<ElTableInstance>()

const { sys_status } = toRefs<any>(proxy?.useDict('sys_status' ));

const pd = reactive({
  treeList: <BomLineVO[]>([]),
  treeOptions: <BomLineVO[]>([]),
  buttonLoading: false,
  showSearch: true,
  isExpandAll: true,
  dataText: "请选择物品",
  formLabel: "下级物料",
  ids: <number[]>[],
  loading: false,
  form: <BomLineVO>{},
  queryParams: <BomLineVO>{},
  bomName: '',
  rules: <ElFormRules>{
    id: [{required: true, message: "BOM不能为空", trigger: "blur"}],
    productId: [{required: true, message: "下级物料不能为空", trigger: "blur"}],
    parentId: [{required: true, message: "上级物料不能为空", trigger: "blur"}],
    quantity: [{required: true, message: "用量不能为空", trigger: "blur"}],
    status: [{required: true, message: "状态不能为空", trigger: "blur"}],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

function searchProduct(vo: ProductVO[]) {
  pd.form.productId = vo[0].id as number;
  pd.dataText = vo[0].name ? vo[0].name : vo[0].id as string;
}

/** 查询物料列表 */
async function getList() {
  pd.loading = true;
  const res = await listBomLine(pd.queryParams);
  res.data.forEach(item=>{
    item.bomName = pd.bomName;
  })
  pd.treeList = proxy?.handleTree<BomLineVO>(res.data, "productId", "parentId", "children") as BomLineVO[];
  console.log(pd.treeList)
  pd.loading = false;
}

/** 查询物料下拉树结构 */
async function getTreeselect() {
  pd.treeOptions = [];
  let data: BomLineVO = {};
  data.id = Number(route.query.id as string);
  data.productId = Number(route.query.productId as string);
  data.productName = "顶级节点";
  data.children = pd.treeList;
  pd.treeOptions.push(data);
}

// 取消按钮
function cancel() {
  reset();
  pd.dialog.visible = false;
}

// 表单重置
function reset() {
  pd.form = {};
  pd.dataText = "请选择物品";
  pd.ids = [Number(route.query.productId as string)];
  pd.form.id = Number(route.query.id as string);
  pd.form.parentId = Number(route.query.productId as string);
  treeFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row?: BomLineVO) {
  reset();
  getTreeselect();
  if (row && row.id) {
    pd.form.parentId = row.productId;
    if (row.parentIds && row.childIds) {
      pd.ids = Array.from(new Set([...row.parentIds as number[], ...row.childIds as number[], row.productId as number]));
    } else {
      pd.ids = [row.productId as number, ...row.parentIds as number[]];
    }
  } else {
    pd.form.parentId = Number(route.query.productId as string);
    pd.form.status = '0';
  }
  pd.formLabel = "下级物料";
  pd.dialog.visible = true;
  pd.dialog.title = "添加物料";
}

/** 展开/折叠操作 */
function handleToggleExpandAll() {
  pd.isExpandAll = !pd.isExpandAll;
  toggleExpandAll(pd.treeList, pd.isExpandAll)
}

/** 展开/折叠操作 */
function toggleExpandAll(data: BomLineVO[], status: boolean) {
  data.forEach((item) => {
    treeTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
async function handleUpdate(row: BomLineVO) {
  reset();
  Object.assign(pd.form, row);
  pd.dataText = row.productName as string;
  if (row.parentIds && row.childIds) {
    pd.ids = Array.from(new Set([...row.parentIds as number[], ...row.childIds as number[], row.productId as number]));
  } else {
    pd.ids = [row.productId as number, ...row.parentIds as number[]];
  }
  pd.form.oldLine = row;
  pd.formLabel = "物料";
  pd.dialog.visible = true;
  pd.dialog.title = "修改物料";
}

/** 提交按钮 */
function submitForm() {
  treeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.dialog.title === "修改物料") {
        await updateBomLine(pd.form).finally(() => pd.buttonLoading = false);
      } else {
        await addBomLine(pd.form).finally(() => pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row: BomLineVO) {
  await proxy?.$modal.confirm('是否确认删除物料为:"' + row.productName + '"的数据项？');
  pd.loading = true;
  await delBomLine(row).finally(() => pd.loading = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}

onMounted(() => {
  pd.queryParams.id = Number(route.query.id as string);
  pd.queryParams.parentId = Number(route.query.productId as string);
  pd.bomName = route.query.bomName as string;
  getList();
});
</script>
